//
//  ScoreViewController.m
//  PlayBall
//
//  Created by Jdd‘s macbook on 13-9-9.
//
//

#import "JddScoreViewController.h"
#import "JddJQToastView.h"
#import "NoticeViewController.h"
#import "SBJsonParser.h"
#import "HUD.h"

@interface JddScoreViewController ()
{
    BOOL isSending;
    UIButton *button1;
    UIButton *button2;
}
@end

@implementation JddScoreViewController
SHARED_VIEW_CONTROLLER_IMPLEMENT(JddScoreViewController);

- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self.navigationItem setHidesBackButton:YES];
    resultArray = [[NSMutableArray alloc] init];
    refreshArray = [[NSMutableArray alloc] init];
    tableDataArray = [[NSMutableArray alloc] init];
    matchState = 1;
    self.btn1.selected = YES;
    [self initAudioPlayer];
    [self initSelectView];
    //初始化浮层后面的遮挡view
    bgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height+100)];
    bgBtn.backgroundColor = [UIColor clearColor];
    [bgBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bgBtn];
    bgBtn.hidden = YES;
}
- (void)btnClick
{
    selectView.hidden = YES;
    bgBtn.hidden = YES;
}

- (void)initSelectView
{
    selectView = [[UIView alloc] initWithFrame:CGRectMake(40, 5, 220, 55)];
    selectView.backgroundColor = [UIColor colorWithRed:249/255.0f green:249/255.0f blue:249/255.0f alpha:1.0];
    selectView.layer.cornerRadius = 8;
    [self.view addSubview:selectView];
    
    button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(20, 10, 80, 35);
    [button1 setTitle:@"竞彩足球" forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIColor *selectTitleColor = [UIColor colorWithRed:252/255.0f green:76/255.0f blue:75/255.0f alpha:1.0];
    
    [button1 setBackgroundImage:[UIImage imageNamed:@"button"] forState:UIControlStateNormal];
    [button1 setTitleColor:selectTitleColor forState:UIControlStateSelected];
    [button1 setBackgroundImage:[UIImage imageNamed:@"buttonSelected"] forState:UIControlStateHighlighted];
    [button1 setBackgroundImage:[UIImage imageNamed:@"buttonSelected"] forState:UIControlStateSelected];
    [button1 setTintColor:[UIColor blackColor]];
    button1.titleLabel.font = [UIFont systemFontOfSize:15];
    [button1 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    button1.tag = 1;
    button1.selected = YES;
    [selectView addSubview:button1];
    
    button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(120, 10, 80, 35);
    [button2 setTitle:@"北京单场" forState:UIControlStateNormal];
    [button2 setBackgroundImage:[UIImage imageNamed:@"button"] forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button2 setTitleColor:selectTitleColor forState:UIControlStateSelected];
    [button2 setBackgroundImage:[UIImage imageNamed:@"buttonSelected"] forState:UIControlStateHighlighted];
    [button2 setBackgroundImage:[UIImage imageNamed:@"buttonSelected"] forState:UIControlStateSelected];
    [button2 setTintColor:[UIColor blackColor]];
    button2.titleLabel.font = [UIFont systemFontOfSize:15];
    [button2 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    button2.tag = 2;
    [selectView addSubview:button2];
    selectView.hidden = YES;
}


-(void)initAudioPlayer
{
    //进球
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Jdddingdong" ofType:@"mp3"];
    if (path) {
        jqPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:path]error:nil];
        [jqPlayer prepareToPlay];
        jqPlayer.numberOfLoops = 1;
        jqPlayer.volume = 0.5f;
    }
    //红黄牌
    NSString *path2 = [[NSBundle mainBundle] pathForResource:@"Jddshaozi" ofType:@"mp3"];
    if (path2) {
        hhPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:path2]error:nil];
        [hhPlayer prepareToPlay];
        hhPlayer.numberOfLoops = 1;
        hhPlayer.volume = 0.5f;
    }
}
- (void)pushNewView
{
    NoticeViewController *noticeView = [[NoticeViewController alloc] init];
    [self.navigationController pushViewController:noticeView animated:YES];
}
- (void)loadLine
{
    self.btn1.layer.borderColor = BORDER_COLOR;
    self.btn1.layer.borderWidth = 0.5;
    
    self.btn2.layer.borderColor = BORDER_COLOR;
    self.btn2.layer.borderWidth = 0.5;
    
    self.btn3.layer.borderColor = BORDER_COLOR;
    self.btn3.layer.borderWidth = 0.5;
    
    self.btn4.layer.borderColor = BORDER_COLOR;
    self.btn4.layer.borderWidth = 0.5;
    
    self.btn5.layer.borderColor = BORDER_COLOR;
    self.btn5.layer.borderWidth = 0.5;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"PageThree"];
    [MobClick event:@"TAB-Score"];

    [self loadLine];
    isSending = NO;
    
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor clearColor];
        button.frame = CGRectMake(0, 0, 40, 30);
        [button setTitle:@"资讯" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button addTarget:self action:@selector(pushNewView) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        self.navigationItem.rightBarButtonItem = rightItem;
    
    btnTitleBG = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnTitleBG setTitle:@"竞彩足球" forState:UIControlStateNormal];
    btnTitleBG.titleLabel.textAlignment = NSTextAlignmentCenter;
    btnTitleBG.frame = CGRectMake(90, 0, SCREEN_WIDTH-180, 30);
    [btnTitleBG addTarget:self action:@selector(selectType) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *jianTou = [[UIImageView alloc] initWithFrame:CGRectMake(110, 10, 13, 10)];
    jianTou.image = [UIImage imageNamed:@"navBar_down.png"];
    [btnTitleBG addSubview:jianTou];
//    [self.navigationItem.titleView addSubview:navTitleView]; 这样写是不对的
    self.navigationItem.titleView = btnTitleBG;
    //赛事筛选
    [self.saiShiBtn addTarget:self action:@selector(matchList) forControlEvents:UIControlEventTouchUpInside];
    button1.selected = YES;
    button2.selected = NO;
    
    //显示tabbar
    [self setJddTabBarHidden:NO];
    [self setTabBarItemSelect:4];
    
    //删除关注中开赛时间过去48小时的
    [self removeTwoDaysAgoForFavoriteData];
    //第一次请求不发送lastTime字段，根据-1判断
    NSString *jczq = [NSString stringWithFormat:@"%d", LOTTERY_TYPE_ID_FOOTBALL];
    [self initDataWithLastTime:@"-1" AndLotterId:jczq];
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    [self refresh2];
}

-(void)matchList
{
    sAlert = [JddselectMatchDialog getInstanceView];
    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:resultArray.count];
    
    for(NSMutableDictionary *d in resultArray){
        [array addObject:[d mutableCopy]];
    }
    
    sAlert.tableDataArray = array;
    sAlert.delegate = self;
    [sAlert show];
}

-(void)removeTwoDaysAgoForFavoriteData
{
    NSString *favoriteScores = [NSString stringWithFormat:FAVORITE_SCORES, [JddCommonFunction thisDocumentPath]];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:favoriteScores];
    if ([[NSFileManager defaultManager] fileExistsAtPath:favoriteScores isDirectory:NO])
        {
        NSMutableArray *arr = [NSMutableArray array];
        NSMutableDictionary *dic = [dictionary objectForKey:self.lotterId];
        for(NSString *d in dic){
            NSString *dateTime = [[dic objectForKey:d] objectForKey:@"i3"];
            NSCalendar *calendar = [NSCalendar currentCalendar];
            unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
            NSDateComponents *components = [calendar components:unitFlags fromDate:[NSDate date]];
            NSInteger iCurYear = [components year];  //当前的年份
            
            dateTime = [NSString stringWithFormat:@"%d-%@:00", iCurYear, dateTime];
            
            NSDate *startDate = [JddCommonFunction NSStringToNSDate:dateTime];
            
            //            NSDate *endDate = [NSDate date];
            //            NSTimeZone *zone = [NSTimeZone systemTimeZone];
            //            NSInteger intervalSDate = [zone secondsFromGMTForDate: endDate];
            //            endDate = [endDate dateByAddingTimeInterval: intervalSDate];
            
            NSTimeInterval  timeInterval = [startDate timeIntervalSinceNow];
            timeInterval = -timeInterval;
            long day = timeInterval/(60 * 60 * 24);
            if (day > 1) {
                [arr addObject:d];
            }
        }
        for(NSString *s in arr){
            [dic removeObjectForKey:s];
        }
        [dictionary writeToFile:favoriteScores atomically:YES];
        }
}

- (IBAction)titleAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    self.btn1.selected = NO;
    self.btn2.selected = NO;
    self.btn3.selected = NO;
    self.btn4.selected = NO;
    self.btn5.selected = NO;
    
    btn.selected = YES;
    [self selectResultDataWithTag:btn.tag];
}

-(void)selectResultDataWithTag:(int)tag
{
    matchState = tag;
    [self changeTableViewData];
}

-(void)changeTableViewData
{
    [tableDataArray removeAllObjects];
    NSMutableArray *tempResultArray = [resultArray mutableCopy];
    // 根据状态筛选
    switch (matchState) {
            //全部
        case 1:
            break;
            //未开赛
        case 2:
            for(NSDictionary *resultDic in resultArray){
                NSString *stateStr = [resultDic objectForKey:@"i4"];
                if (!([stateStr rangeOfString:@"未"].location != NSNotFound || [stateStr isEqualToString:@"延"] || [stateStr isEqualToString:@"推迟开赛"])) {
                    [tempResultArray removeObject:resultDic];
                }
            }
            break;
            //进行中
        case 3:
            for(NSDictionary *resultDic in resultArray){
                NSString *stateStr = [resultDic objectForKey:@"i4"];
                if (([stateStr rangeOfString:@"未"].location != NSNotFound || [stateStr isEqualToString:@"延"] || [stateStr isEqualToString:@"推迟开赛"] || [stateStr isEqualToString:@"完"] || [stateStr isEqualToString:@"弃赛"] || [stateStr isEqualToString:@"取消"])) {
                    [tempResultArray removeObject:resultDic];
                }
            }
            break;
            //已完场
        case 4:
            for(NSDictionary *resultDic in resultArray){
                NSString *stateStr = [resultDic objectForKey:@"i4"];
                if (!([stateStr isEqualToString:@"完"] || [stateStr isEqualToString:@"弃赛"] || [stateStr isEqualToString:@"取消"])) {
                    [tempResultArray removeObject:resultDic];
                }
            }
            break;
            //我的关注
        case 5:
            tempResultArray = [self getIsChecks];
            break;
        default:
            break;
    }
    //只显示筛选出的数据
    for(NSDictionary *d in tempResultArray){
        if ([[d objectForKey:@"isSelected"] boolValue]) {
            [tableDataArray addObject:d];
        }
    }
    [self.listTable reloadData];
}

-(void)initDataWithLastTime:(NSString *)lastTime AndLotterId:(NSString *)lotterId
{
    self.lastTime = lastTime;
    self.lotterId = lotterId;
}

-(void)refresh2
{
    if (!isSending) {
        JddScoreHTTPRequest *sr = [JddScoreHTTPRequest sharedInstance];
        sr.delegate = self;
        sr.lastTime = self.lastTime;
        sr.lotterId = self.lotterId;
        [sr start];
        isSending = YES;
    }
    [self setFavoriteCoutContent];
}


-(void)ScoreHTTPRequestResult:(id)result
{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    //第一次请求完成后，lastTime=0
    BOOL isNeedOut = false;
    NSString *strTem = result;
    NSRange foundObj=[strTem rangeOfString:@"异常信息,请联系客服" options:NSCaseInsensitiveSearch];
    if (foundObj.length>0) {
        [HUD showToast:@"哎呀，获取数据失败，请稍后在试！"];
        isNeedOut = true;
    }
    foundObj = [strTem rangeOfString:@"\"Code\": -1" options:NSCaseInsensitiveSearch];
    if (foundObj.length>0) {
        [HUD showToast:@"哎呀，获取数据失败，请稍后在试！"];
        isNeedOut = true;;
    }

    if ([self.lastTime isEqualToString:@"-1"]) {
        resultArray = [result objectFromJSONString];
        if (resultArray.count > 0) {
            self.lastTime = @"0";
        }else{
            self.lastTime = @"-1";
        }
        //加入字段 isLight
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:resultArray.count];
        for(int i = 0; i < resultArray.count && isNeedOut == false; i ++){
            //深拷贝
            NSMutableDictionary *dic = [[resultArray objectAtIndex:i] mutableCopy];
            [dic setObject:@"0" forKey:@"isLight"];
            [dic setObject:@"1" forKey:@"isSelected"];
            
            [array addObject:dic];
        }
        resultArray = array;
        [self.listTable reloadData];
        isSending = NO;
        //5秒执行一次
        [timer invalidate];
        timer =  [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(refresh2) userInfo:nil repeats:YES];
    }else{
        //非第一次数据
        NSDictionary *resultDic = [result objectFromJSONString];
        if (resultDic.count > 0) {
            //其它类型mid = 4031347; s = "90+";
            if ([resultDic isKindOfClass:[NSArray class]]) {
                refreshArray = [result objectFromJSONString];
            }else{
                //正常类型
                NSArray *array = [resultDic allKeys];
                if ([array containsObject:@"ZqMobileLastMatch"]) {
                    refreshArray = [resultDic objectForKey:@"ZqMobileLastMatch"];
                    self.lastTime = [resultDic objectForKey:@"LastTime"];
                }
            }
            //加入字段
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:refreshArray.count];
            for(int i = 0; i < refreshArray.count; i ++){
                //深拷贝
                NSMutableDictionary *dic = [[refreshArray objectAtIndex:i] mutableCopy];
                NSArray *keys = dic.allKeys;
                
                if (![keys containsObject:@"isLight"]) {
                    [dic setObject:@"0" forKey:@"isLight"];
                }
                
                if (![keys containsObject:@"isSelected"]) {
                    [dic setObject:@"1" forKey:@"isSelected"];
                }
                [array addObject:dic];
            }
            refreshArray = array;
        }
        //更新数据
        [self refreshDataArray];
    }
    // 根据状态筛选
    [self changeTableViewData];
}

-(BOOL)getIsCheckWithScoreId:(NSString *)scoreId
{
    NSString *favoriteScores = [NSString stringWithFormat:FAVORITE_SCORES, [JddCommonFunction thisDocumentPath]];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:favoriteScores];
    NSMutableDictionary *dic = [dictionary objectForKey:self.lotterId];
    if ([dic objectForKey:scoreId]) {
        return YES;
    }else{
        return NO;
    }
}

-(NSMutableArray *)getIsChecks
{
    NSMutableArray *arr = [NSMutableArray array];
    NSString *favoriteScores = [NSString stringWithFormat:FAVORITE_SCORES, [JddCommonFunction thisDocumentPath]];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:favoriteScores];
    NSMutableDictionary *dic = [dictionary objectForKey:self.lotterId];
    for(NSDictionary *resultDic in resultArray){
        NSString *newMatchID = [resultDic objectForKey:@"i1"];
        if ([dic objectForKey:newMatchID]) {
            [dic setObject:resultDic forKey:newMatchID];
            [dictionary setObject:dic forKey:self.lotterId];
            [dictionary writeToFile:favoriteScores atomically:YES];
        }
    }
    for(NSString *s in dic){
        [arr addObject:[dic objectForKey:s]];
    }
    return arr;
}

-(void)setFavoriteCoutContent
{
    NSString *favoriteScores = [NSString stringWithFormat:FAVORITE_SCORES, [JddCommonFunction thisDocumentPath]];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:favoriteScores];
    NSMutableDictionary *dic = [dictionary objectForKey:self.lotterId];
    int count = [[dic allKeys] count];
    if (count > 0) {
        self.favoriteCout.hidden = NO;
        [self.favoriteCout setText:[NSString stringWithFormat:@"%d", count]];
    }else{
        self.favoriteCout.hidden = YES;
    }
}

-(void)refreshDataArray
{
    if (refreshArray.count > 0) {
        NSDictionary *firstDic = [refreshArray objectAtIndex:0];
        NSArray *keys = [firstDic allKeys];
        //用于交换数据
        NSMutableArray *tempResultArray = [resultArray mutableCopy];
        //正常格式
        if ([keys containsObject:@"j1"]) {
            for(NSDictionary *resultDic in resultArray){
                NSString *oldmatchID = [resultDic objectForKey:@"i1"];
                for(NSDictionary *refreshDic in refreshArray){
                    NSString *newmatchID = [refreshDic objectForKey:@"j1"];
                    if ([oldmatchID isEqualToString:newmatchID]) {
                        //替换数据
                        NSMutableDictionary *newDic = [resultDic mutableCopy];
                        NSUInteger index = [tempResultArray indexOfObject:resultDic];
                        [tempResultArray removeObject:resultDic];
                        //进球
                        NSString *j3 = [NSString stringWithFormat:@"%@", [refreshDic objectForKey:@"j3"]];
                        NSString *i8 = [NSString stringWithFormat:@"%@", [newDic objectForKey:@"i8"]];
                        NSString *j4 = [NSString stringWithFormat:@"%@", [refreshDic objectForKey:@"j4"]];
                        NSString *i12 = [NSString stringWithFormat:@"%@", [newDic objectForKey:@"i12"]];
                        if (!([j3 isEqualToString:i8]) || !([j4 isEqualToString: i12])) {
                            //弹出提示信息
                            JddJQToastView *t = [JddJQToastView getInstanceView];
                            t.name.text = [NSString stringWithFormat:@"%@", [newDic objectForKey:@"i2"]];
                            t.time.text = [NSString stringWithFormat:@"%@", [refreshDic objectForKey:@"j2"]];
                            t.hteam.text = [NSString stringWithFormat:@"%@", [newDic objectForKey:@"i5"]];
                            t.vteam.text = [NSString stringWithFormat:@"%@", [newDic objectForKey:@"i9"]];
                            t.hscore.text = [NSString stringWithFormat:@"%@", [refreshDic objectForKey:@"j3"]];
                            t.vscore.text = [NSString stringWithFormat:@"%@", [refreshDic objectForKey:@"j4"]];
                            
                            t.frame = CGRectMake(0, 0, 280, 71);
                            CGPoint point = self.view.center;
                            point.y = 330;
                            NSValue *p = [NSValue valueWithCGPoint:point];
                            [self.view showToast:t duration:2.0 position:p];
                            
                            //播放提示音
                            if (![[USER_DEFAULT objectForKey:@"jq"] boolValue]) {
                                [self playWithMp3Name:0];
                            }
                            [newDic setValue:@"1" forKey:@"isLight"];
                        }
                        // 红黄牌变动声音提示 旧 显示 主队红i6黄i7 客队红i10 黄i11 刷新
                        // 主队红j6黄j7 客队红j9 黄j10
                        NSString *j6 = [NSString stringWithFormat:@"%@", [refreshDic objectForKey:@"j6"]];
                        NSString *i6 = [NSString stringWithFormat:@"%@", [newDic objectForKey:@"i6"]];
                        NSString *j7 = [NSString stringWithFormat:@"%@", [refreshDic objectForKey:@"j7"]];
                        NSString *i7 = [NSString stringWithFormat:@"%@", [newDic objectForKey:@"i7"]];
                        
                        NSString *j9 = [NSString stringWithFormat:@"%@", [refreshDic objectForKey:@"j9"]];
                        NSString *i10 = [NSString stringWithFormat:@"%@", [newDic objectForKey:@"i10"]];
                        NSString *j10 = [NSString stringWithFormat:@"%@", [refreshDic objectForKey:@"j10"]];
                        NSString *i11 = [NSString stringWithFormat:@"%@", [newDic objectForKey:@"i11"]];
                        
                        if (!([j6 isEqualToString: i6]) || !([j7 isEqualToString:i7])
                            || !([j9 isEqualToString:i10]) || !([j10 isEqualToString:i11])) {
                            // 红黄牌播放声音
                            if (![[USER_DEFAULT objectForKey:@"hhp"] boolValue]) {
                                [self playWithMp3Name:1];
                            }
                        }
                        [newDic setValue:[refreshDic objectForKey:@"j2"] forKey:@"i4"];
                        [newDic setValue:[refreshDic objectForKey:@"j6"] forKey:@"i6"];
                        [newDic setValue:[refreshDic objectForKey:@"j7"] forKey:@"i7"];
                        [newDic setValue:[refreshDic objectForKey:@"j3"] forKey:@"i8"];
                        [newDic setValue:[refreshDic objectForKey:@"j9"] forKey:@"i10"];
                        [newDic setValue:[refreshDic objectForKey:@"j10"] forKey:@"i11"];
                        [newDic setValue:[refreshDic objectForKey:@"j4"] forKey:@"i12"];
                        [newDic setValue:[refreshDic objectForKey:@"j5"] forKey:@"i13"];
                        [newDic setValue:[refreshDic objectForKey:@"j2"] forKey:@"i4"];
                        [tempResultArray insertObject:newDic atIndex:index];
                    }
                }
            }
            //非正常数据mid = 4031347; s = "90+";
        }else{
            for(NSDictionary *resultDic in resultArray){
                NSString *oldmatchID = [resultDic objectForKey:@"i1"];
                for(NSDictionary *refreshDic in refreshArray){
                    NSString *newmatchID = [refreshDic objectForKey:@"mid"];
                    if ([oldmatchID isEqualToString:newmatchID]) {
                        //替换数据
                        NSMutableDictionary *newDic = [resultDic mutableCopy];
                        NSUInteger index = [tempResultArray indexOfObject:resultDic];
                        [tempResultArray removeObject:resultDic];
                        [newDic setValue:[refreshDic objectForKey:@"s"] forKey:@"i4"];
                        [tempResultArray insertObject:newDic atIndex:index];
                    }
                }
            }
        }
        resultArray = tempResultArray;
    }
    isSending = NO;
}

-(void)selectType
{
    if (selectView.hidden == YES) {
        selectView.hidden = NO;
         //添加视图，阻止其他按钮可以被点击
        bgBtn.hidden = NO;
        [self.view bringSubviewToFront:selectView];
    }else{
        selectView.hidden = YES;
        bgBtn.hidden = YES;
    }
    
   
}

- (void)buttonClick:(UIButton *)button
{
    bgBtn.hidden = YES;
    if (button.tag == 1) {
        [btnTitleBG setTitle:@"竞彩足球" forState:UIControlStateNormal];
        NSString *jczq = [NSString stringWithFormat:@"%d", LOTTERY_TYPE_ID_FOOTBALL];
        [self initDataWithLastTime:@"-1" AndLotterId:jczq];
        for (UIButton *btn in selectView.subviews){
            btn.selected = NO;
            button.selected = YES;
        }
        selectView.hidden = YES;
    }
    else if (button.tag == 2){
        [btnTitleBG setTitle:@"北京单场" forState:UIControlStateNormal];
        NSString *bd = [NSString stringWithFormat:@"%d", LOTTERY_TYPE_ID_BD];
        [self initDataWithLastTime:@"-1" AndLotterId:bd];
        for (UIButton *btn in selectView.subviews){
            btn.selected = NO;
            button.selected = YES;
        }
        selectView.hidden = YES;
    }
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    [self refresh2];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectio{
    return [tableDataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    static NSString *CellIdentifier = @"ScoreListItemCellIdentifier";
    JddScoreListItemCell *cell = (JddScoreListItemCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(nil == cell) {
        cell = [JddScoreListItemCell getInstanceView];
    }
    NSDictionary *d = [tableDataArray objectAtIndex:row];
    NSString *i1 = [d objectForKey:@"i1"];
    NSString *i2 = [d objectForKey:@"i2"];
    NSString *i3 = [d objectForKey:@"i3"];
    NSString *i6 = [[d objectForKey:@"i6"] stringValue];
    NSString *i7 = [[d objectForKey:@"i7"] stringValue];
    NSString *i4 = [d objectForKey:@"i4"];
    NSString *i13 = [d objectForKey:@"i13"];
    NSString *i5 = [d objectForKey:@"i5"];
    NSString *i8 = [d objectForKey:@"i8"];
    NSString *i12 = [d objectForKey:@"i12"];
    NSString *i812 = @"-";
    NSString *i9 = [d objectForKey:@"i9"];
    NSString *i10 = [[d objectForKey:@"i10"] stringValue];
    NSString *i11 = [[d objectForKey:@"i11"] stringValue];
    NSString *isLight = [d objectForKey:@"isLight"];
    if (i13) {
        if ([i4 rangeOfString:@"未"].location != NSNotFound || [i4 isEqualToString:@"延"] || [i4 isEqualToString:@"推迟开赛"]) {
            if ([i4 rangeOfString:@"未"].location != NSNotFound) {
                i4 = @"未";
            }
            i13 = @"";
            i812 = @"-";
        }else{
            i13 = [i13 stringByReplacingOccurrencesOfString:@":" withString:@"-"];
            i812 = [NSString stringWithFormat:@"%@-%@", i8, i12];
        }
    }
    
    if (i3) {
        i3 = [JddCommonFunction getScoreDateTimeFormString:i3];
    }
    cell.dic = [d mutableCopy];
    cell.lotterId = self.lotterId;
    if ([i6 isEqualToString:@"0"]) {
        cell.i6.hidden = YES;
    }else{
        cell.i6.hidden = NO;
    }
    if ([i7 isEqualToString:@"0"]) {
        cell.i7.hidden = YES;
    }else{
        cell.i7.hidden = NO;
    }
    
    if ([i10 isEqualToString:@"0"]) {
        cell.i10.hidden = YES;
    }else{
        cell.i10.hidden = NO;
    }
    if ([i11 isEqualToString:@"0"]) {
        cell.i11.hidden = YES;
    }else{
        cell.i11.hidden = NO;
    }
    
    cell.i2.text = i2;
    cell.i3.text = i3;
    cell.i4.text = i4;
    cell.i13.text = i13;
    cell.i5.text = i5;
    cell.i812.text = i812;
    cell.i9.text = i9;
    cell.i6.text = i6;
    cell.i7.text = i7;
    cell.i10.text = i10;
    cell.i11.text = i11;
    //进球选项背景
    if ([isLight isEqualToString:@"0"]) {
//        cell.backgroundColor = [UIColor colorWithPatternImage:LOADIMAGE(@"score_list_item_bg2")];
        cell.backgroundColor = [UIColor whiteColor];
    }else{
//        cell.backgroundColor = [UIColor colorWithPatternImage:LOADIMAGE(@"jdd_score_list_item_bg2hover")];
        cell.backgroundColor = [UIColor redColor];
    }
    //关注
    BOOL isCheck = [self getIsCheckWithScoreId:i1];
    cell.startBtn.selected = isCheck;
    cell.delegate = self;
    return cell;
}

- (void)refreshStartBtn
{
    [self setFavoriteCoutContent];
    [self changeTableViewData];
}

-(NSString *)subStringThreeWithName:(NSString *)name
{
    if (name.length > 3) {
        name = [name substringToIndex:3];
    }
    return name;
}

-(void)selectMatch:(NSMutableArray *)dataArray
{
    NSMutableArray *tempResultArray = [resultArray mutableCopy];
    NSMutableArray *tempTableDataArray = [[NSMutableArray alloc] init];
    
    for(NSDictionary *d in dataArray){
        NSString *content = [d.allKeys objectAtIndex:0];
        NSString *isSelected = [d objectForKey:content];
        
        NSArray *btnText = [content componentsSeparatedByString:@"("];
        NSString *name = [btnText objectAtIndex:0];
        //替换原始数据resultArray
        for(NSMutableDictionary *d in tempResultArray)
            {
            //截取赛事名称
            NSString *content = [self subStringThreeWithName:[[d objectForKey:@"i2"] copy]];
            if([content isEqualToString:name]){
                [d setValue:isSelected forKey:@"isSelected"];
            }
            }
        //替换tableView中的数据tableDataArray
        if ([isSelected isEqualToString:@"1"]) {
            for(NSMutableDictionary *d in tableDataArray)
                {
                //截取赛事名称
                NSString *content = [self subStringThreeWithName:[[d objectForKey:@"i2"] copy]];
                if([content isEqualToString:name]){
                    [tempTableDataArray addObject:d];
                }
                }
        }
    }
    resultArray = tempResultArray;
    tableDataArray = tempTableDataArray;
    [self changeTableViewData];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [MobClick endLogPageView:@"PageThree"];

    [timer invalidate];
}

-(void)playWithMp3Name:(int)playType
{
    if (playType == 0) {
        [jqPlayer stop];
        [jqPlayer play];
    }else{
        [hhPlayer stop];
        [hhPlayer play];
    }
}

@end
